package com.shimao.celnet.payment.controller;

import com.shimao.celnet.payment.form.ASysUserForm;
import com.shimao.celnet.payment.form.SelectTree;
import com.shimao.celnet.payment.model.ASysUser;
import com.shimao.celnet.payment.model.BArea;
import com.shimao.celnet.payment.model.BEstate;
import com.shimao.celnet.payment.service.ASysUserService;
import com.shimao.celnet.payment.service.BAreaService;
import com.shimao.celnet.payment.service.BEstateService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.PasswordHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户管理
 * Created by ensure on 2017/4/22.
 */
@Controller
@RequestMapping("/users")
public class ASysUserController {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private ASysUserService localService;

    @Autowired
    private BAreaService bAreaService;

    @Autowired
    private BEstateService bEstateService;

    /**
     * 分页列表
     *
     * @param formBean     页面对象
     * @param pageActionNm 分页提交按钮名称
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String getAll(@ModelAttribute ASysUserForm formBean, String pageActionNm, Model model) {

        logger.info("执行列表页面初始化开始");
        if (StringUtils.isNotEmpty(formBean.getGuid())) {
            //更新，新增后，重新刷新情况，查询条件清空
            formBean = new ASysUserForm();
        }

        //当前页码设定
        int pageNum = FinalUtil.PAGE_Fist_NUM;

        if (formBean.isIsLastPage()) {
            pageNum = formBean.getPages();
        }

        if (!StringUtils.isEmpty(pageActionNm) && !"0".equals(pageActionNm)) {
            pageNum = Integer.valueOf(pageActionNm);
        }
        formBean = localService.getByPage(formBean, pageNum, FinalUtil.PAGE_LENGHT);
        for (ASysUser user : formBean.getList()) {
            BArea bArea = bAreaService.getByKey(user.getAreaGuid());
            if (bArea != null) {
                user.setAreaGuid(bArea.getAreaName());
            }
            BEstate bEstate = bEstateService.getByKey(user.getEstateGuid());
            if (bEstate != null) {
                user.setEstateGuid(bEstate.getEstateName());
            }
        }
        //页面数据查询结果
        model.addAttribute("formBean", formBean);

        return "user/userList";
    }


    /**
     * 详情初始化
     *
     * @param
     * @return
     */
    @RequestMapping("/info")
    public String getUserInfo(@RequestParam String guid, Model model) {
        if (StringUtils.isEmpty(guid)) {
            guid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        }
        ASysUser user = localService.getByKey(guid);
        //编辑数据取得
        ASysUserForm formBean = new ASysUserForm();
        ASysUser aSysUser = localService.getByKey(guid);
        formBean.setGuid(aSysUser.getGuid());
        formBean.setUserName(aSysUser.getUserName());
        formBean.setPassword(aSysUser.getPassword());
        formBean.setEmail(aSysUser.getEmail());
        formBean.setPhone(aSysUser.getPhone());
        formBean.setRealName(aSysUser.getRealName());
        formBean.setFixedPhone(aSysUser.getFixedPhone());
        formBean.setUnit(aSysUser.getUnit());
        formBean.setGender(aSysUser.getGender());
        if (user != null) {
            BArea bArea = bAreaService.getByKey(user.getAreaGuid());
            if (bArea != null) {
                formBean.setAreaName(bArea.getAreaName());
            }
            BEstate bEstate = bEstateService.getByKey(user.getEstateGuid());
            if (bEstate != null) {
                formBean.setEstateName(bEstate.getEstateName());
            }
        }
        formBean.setTreeList(localService.creatRoleTree(guid));
        model.addAttribute("formBean", formBean);
        return "user/userCenter";
    }

    /**
     * 新增：提交
     *
     * @param
     * @return
     */
    @RequestMapping("/addInfo")
    public String addInfo(@ModelAttribute ASysUserForm formBean, Model model) {
        formBean.setTreeList(localService.creatRoleTree(""));
        model.addAttribute("formBean", formBean);
        return "user/userInfo";
    }

    /**
     * 更新初始化
     *
     * @param
     * @return
     */
    @RequestMapping("/editInfo")
    public String editInfo(@RequestParam String guid, Model model) {

        ASysUserForm formBean = new ASysUserForm();
        //编辑数据取得
        ASysUser aSysUser = localService.getByKey(guid);
        formBean.setGuid(aSysUser.getGuid());
        formBean.setUserName(aSysUser.getUserName());
        formBean.setPassword(aSysUser.getPassword());
        formBean.setEmail(aSysUser.getEmail());
        formBean.setPhone(aSysUser.getPhone());
        formBean.setRealName(aSysUser.getRealName());
        formBean.setFixedPhone(aSysUser.getFixedPhone());
        formBean.setUnit(aSysUser.getUnit());
        formBean.setGender(aSysUser.getGender());
        if (aSysUser != null) {
            BArea bArea = bAreaService.getByKey(aSysUser.getAreaGuid());
            if (bArea != null) {
                formBean.setAreaName(bArea.getAreaName());
            }
            BEstate bEstate = bEstateService.getByKey(aSysUser.getEstateGuid());
            if (bEstate != null) {
                formBean.setEstateName(bEstate.getEstateName());
            }
        }

        formBean.setTreeList(localService.creatRoleTree(guid));
        model.addAttribute("formBean", formBean);
        return "user/userInfo";
    }


    /**
     * 新增保存
     *
     * @param
     * @return
     */
    @RequestMapping("/addSave")
    public @ResponseBody
    Map<String, Object> addSave(@RequestBody @Valid ASysUserForm formBean, BindingResult result) {
        //返回map
        Map<String, Object> returnMap = new HashMap<String, Object>();

        //界面输入验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                returnMap.put(error.getField() + FinalUtil.VALID_MSG, error.getDefaultMessage());
                //验证错误==2
                returnMap.put(FinalUtil.ERROR_CODE, FinalUtil.SAVE_ERR_2);
            }
            return returnMap;
        }


        try {
            //数据新增，用户对应角色guid取得
            Map<String, String> roleGuidMap = new HashMap<String, String>();
            List<SelectTree> treeList = formBean.getTreeList();
            for (SelectTree selectTree : treeList) {
                roleGuidMap.put(selectTree.getGuid(), selectTree.getGuid());
            }
            // 当前用户GUID取得
            ASysUser aSysUser = new ASysUser();
            aSysUser.setUserName(formBean.getUserName());
            aSysUser.setPassword(FinalUtil.USER_PASSWORD);
            aSysUser.setEmail(formBean.getEmail());
            aSysUser.setPhone(formBean.getPhone());
            aSysUser.setRealName(formBean.getRealName());
            aSysUser.setFixedPhone(formBean.getFixedPhone());
            aSysUser.setUnit(formBean.getUnit());
            aSysUser.setGender(formBean.getGender());


            PasswordHelper passwordHelper = new PasswordHelper();
            passwordHelper.encryptPassword(aSysUser);
            localService.save(aSysUser, roleGuidMap);

            //新增成功消息==0
            returnMap.put(FinalUtil.ERROR_CODE, FinalUtil.SAVE_SCU_4);
            logger.debug(FinalUtil.PAGE_ADD_SCU);

        } catch (Exception e) {
            //新增失败消息==1
            returnMap.put(FinalUtil.ERROR_CODE, FinalUtil.SAVE_ERR_1);
            returnMap.put(FinalUtil.ERROR_MSG, FinalUtil.PAGE_ADD_ERR);
            e.printStackTrace();
            logger.error(FinalUtil.PAGE_ADD_ERR);
            logger.error(e);
        }

        return returnMap;
    }

    /**
     * 更新保存
     *
     * @param
     * @return
     */
    @RequestMapping("/editSave")
    public @ResponseBody
    Map<String, Object> editSave(@RequestBody @Valid ASysUserForm formBean, BindingResult result) {
        //返回map
        Map<String, Object> returnMap = new HashMap<String, Object>();

        //界面输入验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                returnMap.put(error.getField() + FinalUtil.VALID_MSG, error.getDefaultMessage());
                //验证错误==2
                returnMap.put(FinalUtil.ERROR_CODE, FinalUtil.SAVE_ERR_2);
            }
            return returnMap;
        }
        //数据新增，用户对应角色guid取得
        Map<String, String> roleGuidMap = new HashMap<String, String>();
        List<SelectTree> aSysRoleList = formBean.getTreeList();
        for (SelectTree selectTree : aSysRoleList) {
            roleGuidMap.put(selectTree.getGuid(), selectTree.getGuid());
        }

        try {
            //数据修改，角色对应权限guid取得
            // 当前用户GUID取得
            ASysUser aSysUser = new ASysUser();
            aSysUser.setGuid(formBean.getGuid());
            aSysUser.setUserName(formBean.getUserName());
            aSysUser.setPassword(formBean.getPassword());
            aSysUser.setEmail(formBean.getEmail());
            aSysUser.setPhone(formBean.getPhone());
            aSysUser.setRealName(formBean.getRealName());
            aSysUser.setFixedPhone(formBean.getFixedPhone());
            aSysUser.setUnit(formBean.getUnit());
            aSysUser.setGender(formBean.getGender());

            localService.update(aSysUser, roleGuidMap);

            //更新成功消息==4，左侧菜单刷新
            returnMap.put(FinalUtil.ERROR_CODE, FinalUtil.SAVE_SCU_4);
            logger.debug(FinalUtil.PAGE_UPD_SCU);
        } catch (Exception e) {
            //新增失败消息
            returnMap.put(FinalUtil.ERROR_CODE, FinalUtil.SAVE_ERR_1);
            returnMap.put(FinalUtil.ERROR_MSG, FinalUtil.PAGE_UPD_ERR);
            e.printStackTrace();
            logger.error(FinalUtil.PAGE_UPD_ERR);
            logger.error(e);
        }

        return returnMap;
    }


    /**
     * 删除
     *
     * @param
     * @return
     */
    @RequestMapping("/delete")
    public @ResponseBody
    Map<String, Object> delete(@RequestBody String guid) {
        //返回map
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            //删除角色
            localService.delete(guid);

            //成功消息==0
            returnMap.put(FinalUtil.ERROR_CODE, FinalUtil.SAVE_SCU_0);
            logger.debug(FinalUtil.PAGE_DEL_SCU);
        } catch (Exception e) {
            //失败消息
            returnMap.put(FinalUtil.ERROR_CODE, FinalUtil.SAVE_ERR_1);
            returnMap.put(FinalUtil.ERROR_MSG, FinalUtil.PAGE_DEL_ERR);
            e.printStackTrace();
            logger.error(FinalUtil.PAGE_DEL_ERR);
            logger.error(e);
        }

        return returnMap;
    }


}
